package com.cloudpivot.receivales.ding.robot.service.baidu;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 百度 NPL 自然语言服务
 * 使用rest 调用
 */
@Service
@Slf4j
public class BaiduNPLServiceImpl {

    /**
     * 对应百度 文本相似度的模型
     */
    @Value("${baidu.apikey}")
    private String apiKey1;
    @Value("${baidu.secretkey}")
    private String secretKey1;

    @Autowired
    private BaiduAuthServiceImpl baiduAuthService;


    /**
     * 百度 短文本相似度 服务
     */
    public JSONObject embSimService(String one, String two) {

        String simnetUrl = "https://aip.baidubce.com/rpc/2.0/nlp/v2/simnet";
        String requestUrl = String.format("%s?access_token=%s&charset=UTF-8", simnetUrl, baiduAuthService.getToken(apiKey1,secretKey1));
        JSONObject reqJson = new JSONObject();
        reqJson.put("text_1", one);
        reqJson.put("text_2", two);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> req = new HttpEntity<>(reqJson.toString(), headers);
        JSONObject retJson = restTemplate.postForObject(requestUrl, req, JSONObject.class);
        log.info("返回结果:-------->{}", JSONObject.toJSONString(retJson));
        return retJson;
    }

    /**
     * 百度 语义相似度
     * @param oneStr
     * @param twoStr
     * @return
     */
    public void wordEmbSimServiceForRest(String oneStr, String twoStr) {
        String simnetUrl = "https://aip.baidubce.com/rpc/2.0/nlp/v2/word_emb_sim";
        String requestUrl = String.format("%s?access_token=%s&charset=UTF-8", simnetUrl, baiduAuthService.getToken(apiKey1,secretKey1));
        JSONObject reqJson = new JSONObject();
        reqJson.put("word_1", oneStr);
        reqJson.put("word_2", twoStr);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> req = new HttpEntity<>(reqJson.toString(), headers);
        JSONObject retJson = restTemplate.postForObject(requestUrl, req, JSONObject.class);
        log.info("返回结果:-------->{}", JSONObject.toJSONString(retJson));
    }
}
